<template>
  <view class="box p-x-32 p-y-26" style="padding-bottom: 200rpx !important;">
    <uv-navbar placeholder title="订单确认" :autoBack="true"></uv-navbar>
    <view class="address p-x-26 p-y-32" v-if="addressData?.name">
      <view class="flex aling-ali">
        <view>
          <uv-image width="38rpx" height="38rpx" :src="ASSETSURL + 'positioning.png'"></uv-image>
        </view>
        <view class="font-28 m-l-10">
          {{ addressData?.name }}
        </view>
        <view class="font-24 text-greey m-l-24">
          {{ addressData?.phone }}
        </view>
        <view class="iconDeit" @click="route('pagesA/pages/address/address', { select: true })">
          <uv-image width="40rpx" height="40rpx" :src="ASSETSURL + 'edit.png'"></uv-image>
        </view>
      </view>
      <view class="font-32 font-weight-bold m-t-22">
        {{ addressData?.province + addressData?.city + addressData?.district + addressData?.detail }}
      </view>
    </view>
    <view class="address p-x-26 p-y-32" v-else>
      <view class="flex aling-ali">
        <view>
          <uv-image width="38rpx" height="38rpx" :src="ASSETSURL + 'positioning.png'"></uv-image>
        </view>
        <view class="font-28 m-l-10">
          请选择地址
        </view>
        <view class="iconDeit" @click="route('pagesA/pages/address/address', { select: true })">
          <uv-image width="40rpx" height="40rpx" :src="ASSETSURL + 'edit.png'"></uv-image>
        </view>
      </view>
    </view>
    <view class="main-bg-color p-x-28 p-y-32 m-b-20 m-t-24" style="border-radius: 12rpx;overflow: hidden;"
      v-if="shopList">
      <view class="font-32 font-weight-bold m-b-15">商品清单</view>
      <block v-for="(item, index) in shopList" :key="index">
        <view class="p-24 flex m-t-24">
          <view>
            <uv-image width="192rpx" height="192rpx" :src="item.image" radius="12rpx"></uv-image>
          </view>
          <view class="flex-1 flex-col m-l-20">
            <view class="font-30 flex justify-bet align-ali">
              <view> {{ item.product_name }}</view>
              <view class="font-24 text-840202" v-if="item.add_type == 2" @click="details.open(item)">规格详情</view>
            </view>
            <view class="flex m-t-25 flex-wrap" v-if="!item?.material && item.add_type == 1">
              <view class="content font-28 m-r-20 p-x-14 p-y-6" v-for="(item2, index2) in item.suk.split(',')"
                :key="index2">
                {{ item2 }}
              </view>
            </view>
            <view class="m-b-30 m-t-10 " style="gap: 20rpx" v-else>
              <view class="font-26 font-weight-middle"> 实际周长:{{ item.reality_size }}cm
              </view>
              <view class="font-26 m-t-10 font-weight-middle" v-if="item.line"> {{ item.line.product_name }}({{
                item.line.suk
              }}){{ item.total_number || '0' }}颗珠子
                <!-- {{item.material.map(item2 => item2.product_name + 'x'
                    +
                    item2.number).join('、')}} -->
              </view>
              <view class="font-26 m-t-10 font-weight-middle" v-else> {{ item.suk.line.product_name }}({{
                item.suk.line.suk
              }}){{ item.total_number || '0' }}颗珠子
                <!-- {{item.suk.materials.map(item2 => item2.product_name + 'x'
                  +
                  item2.number).join('、')}} -->
              </view>
            </view>
            <view class="flex m-t-28 justify-bet align-ali">
              <view class="font-28">
                x{{ item.number || 1 }}
              </view>
              <view class="font-36 font-weight-bold text-840202">
                ￥{{ item.number * (item.price / 100) || item.total_price / 100 }}
              </view>
            </view>
          </view>
        </view>
        <u-line color="#D9D9D9" length="100%" margin="30rpx 0" v-if="index != shopList.length - 1"></u-line>
      </block>
    </view>
    <view class="mallProd p-24 flex m-t-24" v-else>
      <view>
        <uv-image width="192rpx" height="192rpx" :src="productData.productData.image" radius="12rpx"></uv-image>
      </view>
      <view class="flex-1 flex-col m-l-20">
        <view class="font-30">
          {{ productData.product.product_name }}
        </view>
        <view class="flex m-t-25 flex-wrap" v-if="productData?.productData?.suk">
          <view class="content font-28 m-r-20 p-x-14 p-y-6"
            v-for="(item, index) in productData.productData.suk.split(',')" :key="index">
            {{ item }}
          </view>
        </view>
        <view class="flex m-t-28 justify-bet align-ali">
          <view class="font-28 text-840202">
            x{{ productData.number }}
          </view>
          <view class="font-36 font-weight-bold text-840202">
            ￥{{ productData.number * (productData?.productData.price / 100) }}
          </view>
        </view>
      </view>
    </view>
    <view class="discountCoupons m-t-24 p-26">
      <view class="coupons font-30 position-relative p-l-30">
        选择优惠券
      </view>
      <view class="discount p-y-28 p-x-26 flex align-ali justify-bet m-t-24"
        @click="route('pagesA/pages/myDesign/coupon', { select: true, diyId: JSON.stringify(diyId), morenyNumber, current: 1 })">
        <view class="font-28">
          优惠券
        </view>
        <view class="flex align-ali">
          <view class="font-30 m-r-10 text-840202">
            {{ couponData?.name || '请选择优惠劵' }}
          </view>
          <view v-if="couponData" class="m-t-6 m-l-16 m-r-16" @click.stop="couponData = null">
            <uv-icon name="close" size="20" color="#CACACA"></uv-icon>
          </view>
          <view class="m-t-6">
            <uv-icon name="arrow-right" size="20" color="#CACACA"></uv-icon>
          </view>
        </view>
      </view>
    </view>
    <view class="discountCoupons m-t-24 p-26">
      <view class="coupons font-30 position-relative p-l-30 m-b-42">
        订单信息
      </view>
      <view class="flex m-t-30 justify-bet align-ali" v-if="shopList && shopList[0]?.material">
        <view class="font-28 text-greey">
          材料小计
        </view>
        <view class="font-28">
          ￥{{ productData.price / 100 || 0 }}
        </view>
      </view>
      <!-- <view class="flex m-t-30 justify-bet align-ali">
        <view class="font-28 text-greey">
          制作费
        </view>
        <view class="font-28">
          ￥0.00
        </view>
      </view> -->
      <view class="flex m-t-30 justify-bet align-ali">
        <view class="font-28 text-greey">
          件数
        </view>
        <view class="font-28">
          {{ productData.number || 1 }}件
        </view>
      </view>
      <!-- <view class="flex m-t-30 justify-bet align-ali"
        v-if="shopList && (shopList[0]?.material || shopList[0]?.suk.materials) && gurationData?.status == 0"> -->
      <view class="flex m-t-30 justify-bet align-ali"
        v-if="shopList?.some(item => item.material || item.suk?.materials)">
        <view class="font-28 text-greey">
          制作费
        </view>
        <view class="font-28">
          ￥{{ totalMakingFee.toFixed(2) }}
        </view>
      </view>
      <view class="flex m-t-30 justify-bet align-ali">
        <view class="font-28 text-greey">
          运费
        </view>
        <view class="font-28">
          ￥{{ tfreight?.price / 100 || '0.00' }}
        </view>
      </view>
      <view class="flex m-t-30 justify-bet align-ali">
        <view class="font-28 text-greey">
          优惠券
        </view>
        <view class="font-28">
          ￥{{ couponData?.amount / 100 || 0 }}
        </view>
      </view>
      <view class="flex m-t-30 justify-bet align-ali">
        <view class="font-28 text-greey">
          合计
        </view>
        <!-- diy商品价格 -->
        <view class="font-28 text-840202 font-weight-bold"
          v-if="shopList?.some(item => item.material || item.suk?.materials) && gurationData?.status == 0">
          ￥{{ totalPrice }}
        </view>
        <view class="font-28 text-840202 font-weight-bold" v-else>
          ￥{{ totalPrice }}
        </view>
      </view>
    </view>
    <view class="fixed-bottom-50 m-x-40">
      <dy-button width="100%" @click="confirmOrder">确认下单</dy-button>
    </view>
    <specificationDetails ref="details"></specificationDetails>
  </view>
</template>

<script setup>
import { getAddressDefault, getFreighttemplate, payOrder, getConfiguration, createOrder } from '@/api/api';
import { ref, onMounted, reactive, computed } from 'vue';
import { useStore } from 'vuex';
import { onReachBottom, onShow, onReady, onLoad } from '@dcloudio/uni-app';
// import { once } from '@dcloudio/uni-app';
import { useCounter } from '@/mixins/userHooks';
const { tool } = useCounter();
import route from '@/uni_modules/uv-ui-tools/libs/util/route.js';
const productData = ref({
  order_id: '',//订单ID
  productData: '',//商品数据
  number: '',//数量
  price: '',//价格
  product: '',//整个商品数据
  buy_mode: '',//1商品购买 2购物车购买
  add_type: '',
  product_id: '',
  product_attr_unique: '',
});
const details = ref(null);
const addressData = ref(null)//地址信息
const couponData = ref(null)//优惠劵信息
const tfreight = ref(null)//运费信息
const shopList = ref(null); //购物车选中数据
const orderSn = ref(null)//订单编号
const gurationData = ref(null)//基础信息
const diyId = ref([])//AIYID
const morenyNumber = ref(null)//总价

onLoad(async (options) => {
  if (options.buy_mode) {
    productData.value.buy_mode = options.buy_mode;
  }
  if (options.product_id) {
    productData.value.product_id = options.product_id;
  }
  if (options.add_type) {
    productData.value.add_type = options.add_type;
  }
  if (options.productData) {
    productData.value.productData = JSON.parse(options.productData);
    console.log(options.price, '-----productDataproductData-----');
    productData.value.number = options.number;
    productData.value.price = options.price;
    productData.value.product_attr_unique = options.product_attr_unique;
    productData.value.product = JSON.parse(decodeURIComponent(options.product));
  }
  if (options.shopList) {
    shopList.value = JSON.parse(decodeURIComponent(options.shopList));
    console.log(shopList.value, '----------');
    productData.value.number = shopList.value.reduce((total, item) => total + (item.number || 1), 0);
    productData.value.price = shopList.value.reduce((total, item) => total + ((item.price || item.total_price) * (item.number || 1)), 0);
    console.log(productData.value.price, 'productData.value.priceproductData.value.price');
  }
  await getConfigurations();
  if (shopList.value) {
    shopList.value.map(item => {
      morenyNumber.value += (item.price || item.total_price) * (item.number || 1)
      if (item.material) {
        item.material.map(item2 => {
          diyId.value.push({ unique: item2.unique, quantity: item2.number })
        })
      }
      if (item.suk?.materials) {
        item.suk?.materials.map(item2 => {
          diyId.value.push({ unique: item2.unique, quantity: item2.number })
        })
      }
    })
  } else if (productData.value) {
    morenyNumber.value = productData.value.number * productData.value.productData.price
  }
})
onShow(async () => {
  uni.$once('getAddress', (res) => {
    addressData.value = res
    getFreight();
  })
  uni.$once('getCoupon', (res) => {
    // console.log(res, '-----')
    couponData.value = res
  })
  if (!addressData.value) {
    await getAddressDefaults();
  }

})
//获取默认地址 
const getAddressDefaults = async () => {
  await getAddressDefault().then(res => {
    console.log(res, '获取默认地址');
    if (res && res.data) {
      addressData.value = res.data
      getFreight();
    }
  })
}
//获取基础信息 
const getConfigurations = async () => {
  await getConfiguration({ type: 4 }).then(res => {
    console.log(res, '获取基础信息');
    gurationData.value = res.data
  })
}

//获取运费
const getFreight = async () => {
  console.log('获取运费1');
  if (addressData.value) {
    await getFreighttemplate({ province: addressData.value.province }).then(res => {
      console.log(res, '获取运费2');
      tfreight.value = res.data
    })
  }
}
//确认下单
const confirmOrder = () => {
  if (!addressData.value) {
    uni.showToast({
      title: '请选择地址',
      icon: 'none'
    })
    return
  }
  createOrder({
    cart_list: shopList.value?.map((item) => ({
      id: item.cart_id,
      number: item.number,
    })),
    buy_mode: productData.value?.buy_mode,
    product_id: productData.value?.product_id,
    product_attr_unique: productData.value?.product_attr_unique,
    add_type: productData.value?.add_type,
    number: productData.value?.number,
  }).then((res) => {
    if (res.code == 1) {
      // 单个商品下单
      let data = {
        order_id: res.data.order_id,
        address_id: addressData.value.id,
        user_coupon_id: couponData.value?.id,
        is_making_number: makingFeeCount.value
      }
      payOrder(data).then(res => {
        if (res.code == 1) {
          tool.requestPayment(res.data.js_config).then(res2 => {
            route(`/pagesA/pages/originality/orderDetails`, { orderSn: res.data.order_sn, add_type: productData.value?.add_type || 1 })
          })
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none',
          })
        }
      })
    } else {
      uni.showToast({ title: res.msg, icon: 'none' });
    }
  });
}

const makingFeeCount = computed(() => shopList.value ? shopList.value.filter(item => item.is_making_fee == 1).length : 0);
const totalMakingFee = computed(() => (gurationData.value?.price / 100 || 0) * makingFeeCount.value);

const totalPrice = computed(() => {
  // 商品总价
  const goodsPrice = productData.value.price / 100 || 0;
  console.log(goodsPrice, productData, 'goodsPrice');
  // 优惠券
  const coupon = couponData.value?.amount / 100 || 0;
  // 运费
  const freight = tfreight.value?.price / 100 || 0;
  // 制作费
  const makingFee = totalMakingFee.value;
  // 合计
  return (Math.max(goodsPrice + makingFee - coupon, 0.01) + freight).toFixed(2);
});
</script>

<style lang="scss">
.box {
  min-height: 100vh;
  background-color: #F6F6F6
}

.address {
  width: 686rpx;
  // height: 178rpx;
  background: #FFF;
  border-radius: 12rpx;

  .iconDeit {
    margin-left: auto;
  }
}

.mallProd {
  width: 686rpx;
  height: 240rpx;
  background: #FFF;
  border-radius: 12rpx;

  .content {
    background: #F3F3F3;
    border-radius: 12rpx;

  }
}

.content {
  background: #F3F3F3;
  border-radius: 12rpx;
}

.discountCoupons {
  width: 686rpx;
  // height: 216rpx;
  background: #FFF;
  border-radius: 12rpx;


  .coupons {
    &::after {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 14rpx;
      height: 14rpx;
      border-radius: 50%;
      background: #840202;
    }
  }

  .discount {
    width: 634rpx;
    height: 96rpx;
    background: #F6F6F6;
    border-radius: 12rpx;
  }
}

.fibotm {
  margin: 0 auto;
}
</style>
